#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API连接测试脚本
测试新的后端API服务连接状态
"""

import requests
import json
import time

# 新的API基础URL
BASE_URL = "http://10.163.78.16:8080"

def test_connection():
    """测试基本连接"""
    print("🔍 测试API连接...")
    print(f"API地址: {BASE_URL}")
    print("-" * 50)
    
    # 测试1: 基本连接
    try:
        response = requests.get(f"{BASE_URL}", timeout=10)
        print(f"✅ 基本连接: HTTP {response.status_code}")
        print(f"📝 响应头: {dict(response.headers)}")
        print(f"📝 响应内容预览: {response.text[:400]}...")
        print(f"📝 完整响应长度: {len(response.text)} 字符")
    except Exception as e:
        print(f"❌ 基本连接失败: {e}")
        return False
    
    # 测试2: 健康检查端点
    print("\n🏥 测试健康检查端点...")
    health_endpoints = [
        "/api/health",
        "/api/health/check", 
        "/health",
        "/health/check"
    ]
    
    for endpoint in health_endpoints:
        try:
            url = f"{BASE_URL}{endpoint}"
            response = requests.get(url, timeout=10)
            print(f"✅ {endpoint}: HTTP {response.status_code}")
            if response.status_code == 200:
                print(f"📝 响应: {response.text[:100]}...")
                break
        except Exception as e:
            print(f"❌ {endpoint}: {e}")
    
    # 测试3: 登录端点
    print("\n🔐 测试登录端点...")
    login_data = {
        "username": "admin",
        "password": "admin123"
    }
    
    try:
        response = requests.post(
            f"{BASE_URL}/api/users/login",
            json=login_data,
            headers={"Content-Type": "application/json"},
            timeout=10
        )
        print(f"✅ 登录端点: HTTP {response.status_code}")
        print(f"📝 响应头: {dict(response.headers)}")
        print(f"📝 响应内容: {response.text[:200]}...")
        
        if response.headers.get('content-type', '').startswith('application/json'):
            try:
                json_response = response.json()
                print(f"📊 JSON响应: {json.dumps(json_response, indent=2, ensure_ascii=False)}")
            except:
                print("⚠️ 无法解析JSON响应")
        else:
            print(f"⚠️ 响应类型: {response.headers.get('content-type', 'unknown')}")
            
    except Exception as e:
        print(f"❌ 登录端点测试失败: {e}")
    
    print("\n" + "="*50)
    print("测试完成")

if __name__ == "__main__":
    test_connection() 